/// <reference path = "../shader/ShaderComponent.ts" />

module lcc$render {

const {ccclass, property, menu} = cc._decorator;

@ccclass("lcc$render.EffectSpriteMask")
@menu("i18n:lcc-render.menu_component/EffectSpriteMask")
export class EffectSpriteMask extends ShaderComponent {

    @property(cc.Material)
	_material: cc.Material = null;
	@property({
		type : cc.Material,
		tooltip : "效果材质"
	})
	get material(){
		return this._material;
	}
	set material(value:cc.Material){
		if(this._material != value){
			this._material = value;
			this.renderSystem.setMaterial(0, value);
		}
	}

    @property(cc.SpriteFrame)
	_spriteFrame: cc.SpriteFrame = null;
	@property({
		type : cc.SpriteFrame,
		tooltip : "效果精灵帧"
	})
	get spriteFrame(){
		return this._spriteFrame;
	}
	set spriteFrame(value:cc.SpriteFrame){
		if(this._spriteFrame != value){
			this._spriteFrame = value;
			this.shaderSpriteFrame.spriteFrame = value;
		}
	}

    @property(cc.SpriteFrame)
	_maskFrame: cc.SpriteFrame = null;
	@property({
		type : cc.SpriteFrame,
		tooltip : "效果遮罩帧"
	})
	get maskFrame(){
		return this._maskFrame;
	}
	set maskFrame(value:cc.SpriteFrame){
		if(this._maskFrame != value){
			this._maskFrame = value;
			this.shaderMaskFrame.spriteFrame = value;
		}
	}

	renderSystem:RenderSystem = null;
	shaderSpriteFrame:ShaderSpriteFrame = null;
	shaderMaskFrame:ShaderSpriteFrame = null;

    // LIFE-CYCLE CALLBACKS:

    onEnable () {
		if(!this.shaderSpriteFrame){
			this.shaderSpriteFrame = this.getShaderComponent(ShaderSpriteFrame, "spriteframe");
			if(!this.shaderSpriteFrame){
				let shader = this.addComponent(ShaderSpriteFrame);
				shader.tag = "spriteframe";
				shader.useUV = true;
				shader.useShape = true;
				this.shaderSpriteFrame = shader;
			}
		}
		if(!this.shaderMaskFrame){
			this.shaderMaskFrame = this.getShaderComponent(ShaderSpriteFrame, "maskframe");
			if(!this.shaderMaskFrame){
				let shader = this.addComponent(ShaderSpriteFrame);
				shader.tag = "maskframe";
				shader.useUV = true;
				shader._textureVar.unifMacro.name = "USE_MASK";
				shader._textureVar.unifName = "mask";
				shader._uvVar.attrMacro.name = "USE_MASK";
				shader._uvVar.attrName = "a_uv1";
				this.shaderMaskFrame = shader;
			}
		}
		if(!this.renderSystem){
			this.renderSystem = this.getComponent(RenderSystem);
			if(!this.renderSystem){
				this.renderSystem = this.addComponent(RenderSystem);
			}
		}
		if(CC_EDITOR){
			this.checkMaterial();
		}
	}

	/**
	 * 检查材质
	 */
	async checkMaterial(){
		if(CC_EDITOR){
			if(!this._material){
				this.material = await Utils.getAssetByUUID<cc.Material>(UUID.materials["lcc-2d-sprite_mask"]);
			}
		}
	}
}

}
